<?php

class ResetPasswordsController extends AppController {

    var $name = 'ResetPasswords';
    var $uses = array('User');
    var $components = array('Email');

    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allowedActions = array('search_username', 'genarate_password', 'genRandomString');
    }

    function backstage_index() {
        $this->layout = "admin";
        if (!empty($this->data)) {
            $users = $this->User->find('first', array('conditions' => array('User.id' => $this->data['User']['id'])));
            $this->User->id = $this->data['User']['id'];
            $this->User->saveField('password', $this->Auth->password($this->data['User']['password']));
            $this->Email->to = $users['User']['email'];
            $this->Email->subject = 'New Password of Authentic Avenue!';
            $this->Email->replyTo = 'noreply@authenticavenue.com';
            $this->Email->from = 'Authentic Team<info@authenticavenue.com>';
            $this->Email->template = 'forgetpassword'; // note no '.ctp'
            //Send as 'html', 'text' or 'both' (default is 'text')
            $this->Email->sendAs = 'html'; // because we like to send pretty mail
            //Set view variables as normal
            $this->set('username', $users['User']['username']);
            $this->set('password', $this->data['User']['password']);
            //Do not pass any args to send()
            $this->Email->send();
            $this->Session->setFlash(__('Password has been reset successfully and send to user', true));
        }
    }

    function search_username() {
        $this->layout = false;
        $this->User->recursive = -1;
        $username = $this->User->findByUsername($this->data['username']);
        if ($username) {
            $return_arr['message'] = "Yes";
            $return_arr['pass'] = $username['User']['hash_p'];
            $return_arr['uid'] = $username['User']['id'];
        } else {
            $return_arr['message'] = "No";
        }
        echo json_encode($return_arr);
        $this->autoRender = false;
    }

    function genarate_password() {
        $this->layout = false;
        $rand = $this->genRandomString();
        $return_arr['password'] = $rand;
        echo json_encode($return_arr);
        $this->autoRender = false;
    }

    function genRandomString() {
        $length = 6;
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $string = '';

        for ($p = 0; $p < $length; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }
        return $string;
    }

}

?>